package com.example.docking.controller;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.response.MaterialEntity;
import com.example.docking.dao.jindie.response.MoTaskbillData;
import com.example.docking.dao.jindie.response.OrderList;
import com.example.docking.dao.jindie.response.PurOrderDetailData;
import com.example.docking.dao.jingxin.putJXApplyOrderWcqd;
import com.example.docking.dao.jingxin.putJXApplyOrderWgqd;
import com.example.docking.dao.jingxin.putJXApplyOrderWxqd;
import com.example.docking.httpJX.HttpUrlConnectionExample;
import com.example.docking.service.impl.DataServiceImpl;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

@Controller
public class PurOrderController {
    private static final Logger logger = LoggerFactory.getLogger(PurOrderController.class);
    public boolean SelectPurOrder(String orderCode, String materialNumber) {
        logger.info("监控采购订单");
        Gson gson = new Gson();
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        map.put("material_number", materialNumber);
        DataServiceImpl Service = new DataServiceImpl();
        ApiResult purOrderApiResult = null;
        boolean allSuccessful = true; // 假设所有操作都成功，除非遇到失败
        try {
            purOrderApiResult = Service.SelectDataList(Constants.PUR_ORDER, map, "");
            Type type1 = new TypeToken<ResponseData<GenericDataItem<OrderList>>>() {
            }.getType();
            ResponseData<GenericDataItem<OrderList>> purOrderResponseData = gson.fromJson(purOrderApiResult.getBody(), type1);
            GenericDataItem<OrderList> orderListGenericDataItem = purOrderResponseData.getData();
            List<OrderList> orderList = orderListGenericDataItem.getRows();
            for (OrderList purOrderItem : orderList) {
                logger.info("通知敬信采购订单入库完成修改状态 {}", purOrderItem.getBill_no());
                String id = purOrderItem.getId();
                //查询详情
                PurOrderDetailData purOrderDetailData = selectById(id);
                HttpUrlConnectionExample httpUrlConnectionExample = new HttpUrlConnectionExample();
                //备注存入，生产任务单号
                if (!purOrderDetailData.getRemark().contains(orderCode)) {
                    continue;
                }
                List<MaterialEntity> materialEntityList = purOrderDetailData.getMaterial_entity();
                for (MaterialEntity materialEntity : materialEntityList) {
                    String comment = materialEntity.getComment();
                    Number num = materialEntity.getQty();
                    String orderType = comment.split(":")[1];
                    if ("外协".equals(orderType)) {
                        putJXApplyOrderWxqd applyOrderWxqd = new putJXApplyOrderWxqd();
                        applyOrderWxqd.setOrderCode(orderCode);
                        applyOrderWxqd.setPartName(materialEntity.getMaterial_name());
                        applyOrderWxqd.setPartDrawingNo(materialEntity.getMaterial_number());
                        if (num != null) {
                            applyOrderWxqd.setOutsourcingQuantity(num.doubleValue());
                        }
                        applyOrderWxqd.setActualCompletion(materialEntity.getDelivery_date());
                        applyOrderWxqd.setId(comment.split(":")[0]);
                        logger.info("外协-采购订单-推送到敬信数据 list: {}", gson.toJson(applyOrderWxqd));
                        String response = httpUrlConnectionExample.sendRequestApplyOrderWxqd(gson.toJson(applyOrderWxqd));
                        if (response == null || "".equals(response)) {
                            logger.info("外协-采购订单-推送失败：再次推送");
                            allSuccessful = false; // 标记为失败
                        } else if (response.contains("集成成功")) {
                            // 保持 allSuccessful 的值不变（如果之前是 true，则仍为 true）
                            logger.info("外协-采购订单--推送到敬信成功返回：response: {}", response);
                        } else {
                            logger.info("外协-采购订单--推送失败1：再次推送");
                            logger.info("外协-采购订单-推送失败原因：response: {}", response);
                            allSuccessful = false; // 标记为失败
                        }
                    }
                    if ("外采".equals(orderType)) {
                        putJXApplyOrderWcqd applyOrderWcqd = new putJXApplyOrderWcqd();
                        applyOrderWcqd.setOrderCode(orderCode);
                        applyOrderWcqd.setPartName(materialEntity.getMaterial_name());
                        applyOrderWcqd.setPartDrawingNo(materialEntity.getMaterial_number());
                        if (num != null) {
                            applyOrderWcqd.setQuantity(num.doubleValue());
                        }
                        applyOrderWcqd.setActualTime(materialEntity.getDelivery_date());
                        applyOrderWcqd.setId(comment.split(":")[0]);
                        logger.info("外采-采购订单-推送到敬信数据 list: {}", gson.toJson(applyOrderWcqd));
                        String response = httpUrlConnectionExample.sendRequestApplyOrderWcqd(gson.toJson(applyOrderWcqd));
                        if (response == null || "".equals(response)) {
                            logger.info("外采-采购订单-任务工单的-推送失败：再次推送");
                            allSuccessful = false; // 标记为失败
                        } else if (response.contains("集成成功")) {
                            // 保持 allSuccessful 的值不变
                            logger.info("外采-采购订单-任务工单的-推送到敬信成功返回：response: {}", response);
                        } else {
                            logger.info("外采-采购订单-任务工单的-推送失败2：再次推送");
                            logger.info("外采-采购订单-推送失败原因：response: {}", response);
                            allSuccessful = false; // 标记为失败
                        }
                    }
                    if ("外购".equals(orderType)) {
                        putJXApplyOrderWgqd applyOrderWgqd = new putJXApplyOrderWgqd();
                        applyOrderWgqd.setOrderCode(orderCode);
                        applyOrderWgqd.setPartName(materialEntity.getMaterial_name());
                        applyOrderWgqd.setPartDrawingNo(materialEntity.getMaterial_number());
                        if (num != null) {
                            applyOrderWgqd.setQuantity(num.doubleValue());
                        }
                        applyOrderWgqd.setActualTime(materialEntity.getDelivery_date());
                        applyOrderWgqd.setId(comment.split(":")[0]);
                        logger.info("外购-采购订单-推送到敬信数据 list: {}", gson.toJson(applyOrderWgqd));
                        String response = httpUrlConnectionExample.sendRequestApplyOrderWgqd(gson.toJson(applyOrderWgqd));
                        if (response == null || "".equals(response)) {
                            logger.info("外购-采购订单-任务工单的-推送失败：再次推送");
                            allSuccessful = false; // 标记为失败
                        } else if (response.contains("集成成功")) {
                            // 保持 allSuccessful 的值不变
                            logger.info("外购-采购订单-任务工单的-推送到敬信成功返回：response: {}", response);
                        } else {
                            logger.info("外购-采购订单-任务工单的-推送失败3：再次推送");
                            logger.info("外够-采购订单-推送失败原因：response: {}", response);
                            allSuccessful = false; // 标记为失败
                        }
                    }
                }
            }
            logger.info("Code: {}", purOrderResponseData.getErrcode());
            logger.info("Message: {}", purOrderResponseData.getDescription());
            logger.info("data: {}", purOrderResponseData.getData());
        } catch (Exception e) {
            logger.error("查询采购订单时发生异常", e);
            throw new RuntimeException(e);
        }
        return allSuccessful;
    }

    public static PurOrderDetailData selectById(String id) {
        PurOrderDetailData purOrderDetailData = new PurOrderDetailData();
        Gson gson = new Gson();
        logger.info("根据编号获取采购订单");
        MoTaskbillData moTaskbillData = new MoTaskbillData();
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        DataServiceImpl Service = new DataServiceImpl();
        ApiResult DataResult = null;
        try {
            DataResult = Service.SelectDataList(Constants.PUR_ORDER_DETAIL, map, "");
            Type SaleDataType = new TypeToken<ResponseData<PurOrderDetailData>>() {
            }.getType();
            ResponseData<PurOrderDetailData> responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
            purOrderDetailData = responseSaleData.getData();
            logger.info("code" + responseSaleData.getErrcode());
            logger.info("描述" + responseSaleData.getDescription());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return purOrderDetailData;
    }

    public static void main(String[] args) {
        PurOrderController purOrderRequestController = new PurOrderController();
        purOrderRequestController.SelectPurOrder("", "");
    }
}